<template>
  <div>
    <page-tools>
      <!-- 左侧插槽 -->
      <template #left>
        <div class="tips">
          <i class="el-icon-info" />
          <span>本月: 社保在缴 公积金在缴</span>
        </div>
      </template>
      <!-- 右侧插槽 -->
      <template #right>
        <el-button type="primary" size="small" @click="exportExcel">员工导出</el-button>
        <el-button type="primary" size="small" @click="$router.push('/import')">员工导入</el-button>
        <el-button type="primary" size="small" @click="addEmploy">新增员工</el-button>
      </template>
    </page-tools>

    <el-card style="margin-top: 10px">
      <el-table border :data="list">
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式">
          <template #default="{ row }">
            {{ formatEmployment(row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.timeOfEntry) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="goDetail(row.id)">查看</el-button>
            <el-button type="text" size="small" @click="assignRoles(row.id)">分配角色</el-button>
            <el-button
              type="text"
              size="small"
              @click="delEmploy(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <div style="height: 60px; margin-top: 10px">
      <el-pagination
        :total="total"
        :current-page="params.page"
        :page-size="params.size"
        layout="prev, pager, next"
        @current-change="pageChange"
      />
    </div>

    <!-- 新增弹框组件 -->
    <add-employee
      ref="addRef"
      :visible="visible"
      @close-dialog="closeDialog"
      @updata-list="fetchList"
    />

    <!-- 分配权限弹窗 -->
    <el-dialog
      class="assign-role"
      title="分配角色"
      :visible="showRoleDialog"
      @close="cloesRoleDialog"
      @open="openRoleDialog"
    >
      <!-- 这里准备复选框 -->
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>

      <template #footer>
        <el-button type="primary" size="small" @click="confirmAssign">确定</el-button>
        <el-button size="small" @click="cloesRoleDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import PageTools from '@/components/PageTools/index.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import { getExportData } from '@/utils/excel'
import { getRoleList } from '@/api/setting'
import { assignRoles } from '@/api/employees'
import { getUserDetailById } from '@/api/user'
// 引入弹窗组件
import AddEmployee from './components/add-employee.vue'
export default {
  name: 'Employee',
  components: {
    PageTools,
    AddEmployee
  },
  data() {
    return {
      list: [],
      params: {
        page: 1,
        size: 10
      },
      total: 0,
      visible: false,
      showRoleDialog: false,
      curId: null,
      checkList: [], // 选中项的label值
      roleList: [] // 角色列表
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    // 获取列表展示页面
    async fetchList() {
      const res = await getEmployeeList(this.params)
      this.list = res.rows
      this.total = res.total
    },
    // 格式化聘用形式
    formatEmployment(type) {
      const TYPE = {
        1: '正式',
        2: '非正式员工',
        3: '临时员工',
        4: '老板亲戚'
      }
      return TYPE[type]
    },
    // 格式化时间
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    // 当前页数变化的时候
    pageChange(page) {
      // console.log(page)
      // 让变化的页数赋值给 page
      this.params.page = page
      // 重新获取列表渲染页面
      this.fetchList()
    },
    // 删除功能
    delEmploy(id) {
      this.$confirm('你确认要删除么?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployee(id)
        this.$message.success('删除员工成功')
        this.fetchList()
      }).catch(() => {
        return
      })
    },
    // 打开弹窗
    openDialog() {
      this.visible = true
    },
    // 关闭弹窗
    closeDialog() {
      this.visible = false
    },
    // 新增按钮点击事件
    addEmploy() {
      this.openDialog()
    },
    // 导出
    exportExcel() {
      // 按需导入 什么时候要用导出的功能 什么时候就动态的把这个包加入到项目中 路由懒加载类似
      import('@/vendor/Export2Excel').then(async(excel) => {
        // console.log(excel)
        // 1.export_json_to_excel: 把json格式转化成excel格式 [我们采取的格式]
        // 2.export_table_to_excel: 把table格式转化成excel格式

        // 在基础功能实现的情况下 把静态写死的数据换成 接口数据
        // 1. 调用接口 和获取表格数据的写法是一样的
        const res = await getEmployeeList(this.params)
        // 2. 数据的二次处理 后端返回的数据不能直接用
        const headerRelation = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        const { data } = getExportData(res.rows, headerRelation)
        excel.export_json_to_excel({
          header: Object.keys(headerRelation), // 表头header 必填 要求是一个数组
          data: data, // 表格数据body 要求是一个二维数组
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    goDetail(id) {
      this.$router.push({
        path: '/employeeDetail',
        query: {
          id
        }
      })
    },
    assignRoles(id) {
      this.curId = id // 记录点击的id
      this.showRoleDialog = true
    },
    cloesRoleDialog() {
      this.showRoleDialog = false
    },
    async openRoleDialog() {
      const { rows } = await getRoleList()
      this.roleList = rows

      // 选中数据回填
      const { roleIds } = await getUserDetailById(this.curId)
      this.checkList = roleIds
    },
    async confirmAssign() {
      await assignRoles({
        id: this.curId,
        roleIds: this.checkList
      })
      this.cloesRoleDialog()
      this.$message.success('分配角色成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
